package org.abettor.pushbox.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.abettor.pushbox.activity2.ShowUserDetailActivity;
import org.abettor.pushbox.activity2.SiteMessageActivity;
import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.DownloadMap;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.model.NetAnswerBean;
import org.abettor.pushbox.R;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class QuesstionAnswerListActivity extends ListActivity {
	private int isHasMore;// 判断是否还有更多的数据
	private boolean isLoading = false;// 判断当前的状态，是否处于加载状态
	private Handler mHandler = new Handler();
	private ProgressBar progressBar;// 进度条
	private Date lastAccessTime = null;// 用来存取最后一条记录的基准时间
	private UserMapAdapter userMapAdapter;// 用户的监听器
	private DownloadMap netBeanDown = null;// 用来下载地图的bean
	private int map_id = -1;// 地图的id
	private final int VIEW_USER_DETAIL = Menu.FIRST + 1;// 查看用户详情
	private final int SEND_USER_MSG = Menu.FIRST + 2;// 给用户发送消息的操作
	private final int VIEW_RESULT_DETAIL = Menu.FIRST + 3;// 查看用户的详情

	/*-------------------------------------注册context事件-------------------------*/
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.quesstion_map);
		menu.add(0, VIEW_USER_DETAIL, 1, R.string.view_user_detail);
		menu.add(0, SEND_USER_MSG, 2, R.string.send_msg);
		menu.add(0, VIEW_RESULT_DETAIL, 3, R.string.view_result);
	}

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) aItem
				.getMenuInfo();
		switch (aItem.getItemId()) {
		case VIEW_USER_DETAIL:
			NetAnswerBean bean = (NetAnswerBean) userMapAdapter
					.getItem(info.position);
			doViewUserDetail(bean.getUserId(),bean.getUpor());
			break;
		case SEND_USER_MSG:
			bean = (NetAnswerBean) userMapAdapter.getItem(info.position);
			doSendMsg(bean.getUserId());
			break;
		case VIEW_RESULT_DETAIL:
			doViewResult((int) info.id);
			break;
		}
		return false;
	}

	/*---------------------------------------------------------------------------*/
	private void doViewUserDetail(int id,String nick) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		extras.putString("nick_name", nick);
		in.putExtras(extras);
		in.setClass(QuesstionAnswerListActivity.this,
				ShowUserDetailActivity.class);
		startActivity(in);
	}

	// 发送消息的操作
	private void doSendMsg(int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) id);
		in.putExtras(extras);
		in.setClass(QuesstionAnswerListActivity.this, SiteMessageActivity.class);
		startActivity(in);
	}

	// 点击的listenner
	private class AnswerListItemClickListenner implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			doViewResult((int) id);
		}
	}

	private void doViewResult(int id) {
		Intent in = new Intent();
		Bundle extras = new Bundle();
		extras.putInt("_id", (int) map_id);
		extras.putInt("result_id", (int) id);
		in.putExtras(extras);
		in.setClass(QuesstionAnswerListActivity.this,
				QuesstionShowNetResultActivity.class);
		startActivity(in);
	}

	// 滚动条的监听器
	private class MyOnScrollListener implements OnScrollListener {
		private boolean linloading = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 把totalItemCount剔除掉，因为加入footer，所以剔除掉totalItemCount为1的时候
			if (totalItemCount == 1) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& isHasMore == ParaDownloadRetValue.HASMORE) {
				if (!linloading) {
					linloading = true;
					loadMap();// 加载数据
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							linloading = false;
						}
					}, 4000);
				}
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		protected void loadMap() {
			loadAnswerList();// 获得答案列表的操作
		}
	}

	private void loadAnswerList() {
		// 已经加载时地图就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadAnswerListOperation();// 加载答案列表的操作
			}
		};
		isLoading = true;
		showAnswerProgressBar();// 显示加载中的progressbar
		thread.start();
	}

	// 读取答案列表的实际操作
	private void loadAnswerListOperation() {
		lastAccessTime = userMapAdapter.getLastAccessTime();// 获得最近存取的时间
		String content = netBeanDown.downloadAnswerListStr(map_id,
				lastAccessTime, Config.PAGESIZE);
		dispearProgressBar();// 使加载框消失
		isLoading = false;
		// 读取内容为空，显示加载失败的对话框
		if (content == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 判断是否还有更多的数据
		isHasMore = ParaDownloadRetValue.isHasMoreNetMap(content);
		// 解析数据内容失败，显示加载失败的对话框
		if (isHasMore == ParaDownloadRetValue.ERROR) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		// 解析数据的列表
		final List<NetAnswerBean> reList = ParaDownloadRetValue
				.paraAnswer(content);
		if (reList == null) {
			loadNetMapFailure();// 显示加载失败的对话框
			return;
		}
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				userMapAdapter.addNetAnswerBean(reList);
				userMapAdapter.notifyDataSetChanged();
			}
		});
		// 显示用户的对话框
		showListMapView();
	}

	// show List View
	private void showListMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (QuesstionAnswerListActivity.this.getListView()
						.getVisibility() == View.GONE) {
					QuesstionAnswerListActivity.this.getListView()
							.setVisibility(View.VISIBLE);
					TextView textView = (TextView) QuesstionAnswerListActivity.this
							.findViewById(R.id.no_answer);
					textView.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	/**
	 * 进行加载失败处理的类
	 * 
	 * @author jzh
	 * 
	 */
	private abstract class LoadFailureRunnable implements Runnable {
		@Override
		public void run() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					QuesstionAnswerListActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.error);
			alert.setMessage(QuesstionAnswerListActivity.this
					.getText(R.string.netuser_loadanswer_failure));
			alert.setButton(DialogInterface.BUTTON_POSITIVE,
					QuesstionAnswerListActivity.this
							.getText(R.string.netuser_retry),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 显示加载的对话标签
							showAnswerProgressBar();
							// 重新网络地图的操作
							loadMap();
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE,
					QuesstionAnswerListActivity.this
							.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alert.show();
		}

		public abstract void loadMap();
	}

	// dispear progressBar
	private void dispearProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				int state = QuesstionAnswerListActivity.this.getListView()
						.getVisibility();
				if (state == View.GONE) {// 大对话框，消失的操作
					progressBar = (ProgressBar) QuesstionAnswerListActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.GONE);
				} else {// 小对话框的消失操作
					View view = QuesstionAnswerListActivity.this
							.findViewById(R.id.footor);
					view.setVisibility(View.GONE);
				}
			}
		});
	}

	// 显示加载的对话框
	private void showAnswerProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				TextView textView = (TextView) QuesstionAnswerListActivity.this
						.findViewById(R.id.no_answer);
				textView.setVisibility(View.GONE);
				// 当列表框还没显示时显示大的加载框
				int state = QuesstionAnswerListActivity.this.getListView()
						.getVisibility();
				if (state == View.GONE) {
					progressBar = (ProgressBar) QuesstionAnswerListActivity.this
							.findViewById(R.id.progressBar1);
					progressBar.setVisibility(View.VISIBLE);
				} else {
					View view = QuesstionAnswerListActivity.this.getListView()
							.findViewById(R.id.footor);
					view.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private class UserMapAdapter extends BaseAdapter {
		protected List<NetAnswerBean> netAnswerList;

		/**
		 * 获得最后一次更新时间
		 * 
		 * @return
		 */
		public Date getLastAccessTime() {
			if (netAnswerList == null || netAnswerList.isEmpty()) {
				return null;
			}
			int size = netAnswerList.size();
			NetAnswerBean bean = null;
			synchronized (netAnswerList) {
				bean = netAnswerList.get(size - 1);
			}
			return bean.getUploadDate();
		}

		/**
		 * 向里边加入数据
		 * 
		 * @param bean
		 */
		public void addNetAnswerBean(List<NetAnswerBean> toAdd) {
			if (toAdd == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			Iterator<NetAnswerBean> itr = toAdd.iterator();
			while (itr.hasNext()) {
				NetAnswerBean net = itr.next();
				if (lastTime == null || net.getUploadDate().before(lastTime)) {
					netAnswerList.add(net);
				} else {
					netAnswerList.add(0, net);
				}
			}
		}

		public UserMapAdapter(List<NetAnswerBean> list) {
			this.netAnswerList = list;
		}

		@Override
		public int getCount() {
			synchronized (netAnswerList) {
				return netAnswerList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			synchronized (netAnswerList) {
				return netAnswerList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (netAnswerList) {
				return netAnswerList.get(position).getId();
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			final NetAnswerBean item;
			synchronized (netAnswerList) {
				item = netAnswerList.get(position);
			}
			LayoutInflater inflater = QuesstionAnswerListActivity.this
					.getLayoutInflater();
			ViewGroup theParent = (ViewGroup) inflater
					.inflate(R.layout.quesstion_answer_list_activity_item,
							parent, false);
			TextView uploadTime = (TextView) theParent
					.findViewById(R.id.upload_time);
			TextView msgView = (TextView) theParent
					.findViewById(R.id.answer_msg);
			TextView answerStep = (TextView) theParent
					.findViewById(R.id.answer_step);
			uploadTime.setText(sdf.format(item.getUploadDate()));
			msgView.setText(changeMsgToStr(item));
			answerStep.setText(String.valueOf(item.getCount()));
			return theParent;
		}

		private String changeMsgToStr(NetAnswerBean bean) {
			String str = "";
			str = str
					+ QuesstionAnswerListActivity.this
							.getText(R.string.answer_uploader) + ":";
			str = str + bean.getUpor();
			return str;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.quesstion_answer_list_activity);
		// 获得地图的id
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		map_id = extras.getInt("_id");
		netBeanDown = new DownloadMap(this);
		addFooterView(this.getListView());
		userMapAdapter = new UserMapAdapter(new LinkedList<NetAnswerBean>());
		this.getListView().setAdapter(userMapAdapter);
		this.getListView().setOnScrollListener(new MyOnScrollListener());
		QuesstionAnswerListActivity.this.loadAnswerList();
		// 注册context menu的操作
		registerForContextMenu(this.getListView());
		this.getListView().setOnItemClickListener(
				new AnswerListItemClickListenner());
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	// 增加footer view
	private void addFooterView(ListView listView) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.net_user_map_list_footer, null);
		listView.addFooterView(localView);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	// 显示加载网络地图错误的的对话狂
	private void loadNetMapFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				loadAnswerList();
			}
		});
	}
}
